<template>
  <el-dialog v-model="isShowTransfer" :width="600" center :show-close="false">
    <template #header>
      <title-view title="客户移交" />
    </template>
    <div class="transfer-container" v-loading="isLoading">
      <el-form ref="ruleDialogFormRef" label-width="180px" :model="formData" :rules="addFormRules" status-icon>
        <div class="form-row">
          <el-form-item label="请选择要移交的角色：" prop="roleId" required>
            <select-remote
              v-model="formData.roleId"
              :option-list="roleOptions"
              @change-select="changeRoleSelect"
              @clear-select="clearSelect('role')"
              placeholder="请输入角色名搜索"
              :request-api="roleList"
              :defaultConfig="{ keyword: 'name', label: 'roleName', value: 'roleId' }"
            ></select-remote>
          </el-form-item>
          <el-form-item prop="devolveId" required label-width="10px">
            <select-remote
              v-model="formData.devolveId"
              :option-list="roleRelationNameOptions"
              @change-select="changeRoleRelationNameSelect"
              :request-api="userNameByRoleId"
              @clear-select="clearSelect('relationName')"
              placeholder="请输入员工姓名搜索"
              :params="roleRelationNameParams"
              :defaultConfig="{ keyword: 'userName', label: 'userName', value: 'userId' }"
            ></select-remote>
          </el-form-item>
        </div>
        <el-form-item label="移交给：" prop="assignId" required>
          <el-col :span="11">
            <select-remote
              v-model="formData.assignId"
              :option-list="transferNameOptions"
              @change-select="changeTransferNameSelect"
              :request-api="userNameByRoleId"
              @clear-select="clearSelect('transferName')"
              placeholder="请输入员工姓名搜索"
              :params="transferNameParams"
              :defaultConfig="{ keyword: 'userName', label: 'userName', value: 'userId' }"
            ></select-remote>
          </el-col>
        </el-form-item>
        <el-form-item>
          <div class="tips">注意，移交给的负责人必须有移交角色的权限 移交后不可再还原，请谨慎操作！</div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handelCancel" :disabled="isLoading">取消</el-button>
        <el-button type="primary" @click="handelConfirm" :disabled="isLoading">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { userNameByRoleId, roleList, saveTransferInfo } from "@/apis/clientManager";
import { computed, ref, getCurrentInstance, watch } from "vue";
const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  tableBodyParams: {
    type: Object,
    default: () => ({})
  }
});
const emit = defineEmits(["update:modelValue", "save"]);

/**
 * 移交
 */
const isShowTransfer = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const addFormRules = {
  roleId: { required: true, message: "请选择要移交的角色", trigger: "change" },
  devolveId: { required: true, message: "请选择要移交员工姓名", trigger: "change" },
  assignId: { required: true, message: "请选择移交的员工姓名", trigger: "change" }
};

const formData = ref({
  roleId: "",
  devolveId: "",
  assignId: "",
  loginUserId: ""
});
const roleRelationNameParams = ref({ roleId: "", status: false });
const transferNameParams = ref({ roleId: "", status: true });
const roleOptions = ref([]);
const roleRelationNameOptions = ref([]);
const transferNameOptions = ref([]);
// const getRoleList = async () => {
//   roleList({ name: "" })
//     .then(res => {
//       const data = res.data || [];
//     })
//     .catch(err => {
//       proxy.$modal.msgError("获取角色失败");
//     });
// };
const changeRoleSelect = data => {
  roleRelationNameParams.value = {
    roleId: data.roleId,
    status: false
  };
  transferNameParams.value = {
    roleId: data.roleId,
    status: true
  };

  formData.value.roleId = data.roleId;
  // getUserName({ ...roleRelationNameParams.value, ...{ userName: "" } });
  // getUserName({ ...transferNameParams.value, ...{ userName: "" } });
};
const changeRoleRelationNameSelect = data => {
  formData.value.devolveId = data.userId;
};
const changeTransferNameSelect = data => {
  formData.value.assignId = data.userId;
};
// const getUserName = params => {
//   userNameByRoleId(params)
//     .then(res => {
//       const data = res.data || [];
//       if (!params.status) {
//         roleRelationNameOptions.value = data || [];
//       } else {
//         transferNameOptions.value = data || [];
//       }
//     })
//     .catch(err => {
//       proxy.$modal.msgError("获取角色失败");
//     });
// };
const clearSelect = type => {
  if (type === "role") {
    formData.value.roleId = "";
    formData.value.assignId = "";
    formData.value.devolveId = "";
    roleRelationNameOptions.value = [];
    transferNameOptions.value = [];
    roleRelationNameParams.value = { roleId: "", status: false };
    transferNameParams.value = { roleId: "", status: true };
  }
  if (type === "relationName") {
    formData.value.devolveId = "";
    roleRelationNameOptions.value = [];
  }
  if (type === "transferName") {
    formData.value.assignId = "";
    transferNameOptions.value = [];
  }
};
watch(
  () => formData.value.roleId,
  (newV, oldV) => {
    formData.value.devolveId = "";
    formData.value.assignId = "";
    roleRelationNameOptions.value = [];
    transferNameOptions.value = [];
  }
);

const isLoading = ref(false);
const handelConfirm = () => {
  formData.value.loginUserId = formData.value.assignId;
  proxy.$refs.ruleDialogFormRef.validate(async val => {
    if (!val) {
      return proxy.$modal.msgError("请填写完整信息");
    }
    proxy.$modal
      .confirm("您确定要保存吗？")
      .then(() => {
        isLoading.value = true;
        saveTransferInfo(formData.value)
          .then(res => {
            proxy.$modal.msgSuccess("保存成功");
            setTimeout(() => {
              isShowTransfer.value = false;
              emit("save");
            }, 2500);
          })
          .catch(() => {
            isLoading.value = false;
          });
      })
      .catch(() => {
        isLoading.value = false;
      });
  });
};
const handelCancel = () => {
  isShowTransfer.value = false;
};

// getRoleList();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
.el-form {
  width: 100%;
  .form-row {
    display: flex;
    justify-content: left;
  }
  :deep(.el-select) {
    width: 180px;
  }
  .tips {
    line-height: 20px;
    font-size: 12px;
    color: #606266;
  }
}
.dialog-footer {
  button {
    width: 90px;
    height: 38px;
  }
}
</style>
